﻿import fetch from 'isomorphic-fetch'
import { Toast } from 'antd-mobile'

if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g, '')
  }
}

var T = window.T = {
  host: '', //   这个地方不要动，是预留的配置，如果不走nodejs,就在这个地方配后端的域名。
  weixinHost: '//11543-tech-atom-za-graphene-wechat.test.za-tech.net/',
  get: function (id) {
    return document.getElementById(id)
  },
  trimAll: function (str) {
    if (typeof str !== 'string') {
      return str
    }

    return str.replace(/\s+/g, '')
  },
  showInfo (msg, time) {
    Toast.info(msg, time)
  },
  showSuccess (msg, time) {
    Toast.success(msg, time)
  },
  showError (msg, time = 2) {
    Toast.fail(msg || 'Request error', time)
  },
  showLoading () {
    Toast.loading('loading..', 0)
  },
  hideLoading () {
    Toast.hide()
  },

  tryEval: function (js) {
    var result = null
    if (!js) {
      return result
    }
    if (typeof js !== 'string') {
      return js
    }
    try {
      result = JSON.parse(js)
    } catch (e) {
      console.log('[eval error json解析错误]' + e.message)
    }
    return result
  },

  urlQuery: function (key, url) {
    url = url || location.href
    var reg = new RegExp('[?&#]' + key + '=([^&#]*)', 'i')
    var match = url.match(reg)
    var result

    if (match) {
      try {
        result = decodeURIComponent(match[1]) || ''
        return result
      } catch (e) {
      }
    }
    return ''
  },
  formatDate: function (format, date) { //   "yyyy-MM-dd hh:mm:ss"
    if (!date) return ''
    date = new Date(date)
    var o = {
      'M+': date.getMonth() + 1, // month
      'd+': date.getDate(), // day
      'h+': date.getHours(), // hour
      'm+': date.getMinutes(), // minute
      's+': date.getSeconds(), // second
      'q+': Math.floor((date.getMonth() + 3) / 3), // quarter
      'S': date.getMilliseconds(), // millisecond
      'w': '日一二三四五六'.charAt(date.getDay())
    }
    format = format.replace(/y{4}/i, date.getFullYear())
      .replace(/y{2}/i, date.getFullYear().toString().substring(2))

    for (var k in o) {
      var reg = new RegExp(k)
      format = format.replace(reg, match)
    }
    function match (m) {
      return m.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
    }
    return format
  },
  isArray: function (obj) {
    return Object.prototype.toString.apply(obj) === '[object Array]'
  },
  formatReqData: function (data, percentKeyArr) {
    let arr = []
    for (let key in data) {
      if (key == 'cashBonusOption' || key == 'liabilityCodes') {
        data[key] = data[key] && data[key].join(',')
      }
      if (percentKeyArr && percentKeyArr.indexOf(key) > -1) {
        data[key] = (data[key] / 100).toFixed(2)
      }
      arr.push({
        'customizeDefCode': key,
        'customizeDefValue': data[key]
      })
    }
    return arr
  },
  getAttrObject: function (objArray, key, value) { // 一个对象数组，获取key等于value的对象数组
    objArray = (objArray instanceof Array) ? objArray : [objArray]

    var arr = []
    var item
    var temp
    for (var i = 0; i < objArray.length; i++) {
      item = objArray[i]
      if (item == undefined) {
        continue
      }
      temp = (key instanceof Array) ? item[key[0]][key[1]] : item[key]

      if (value instanceof Array) {
        if (value.indexOf(temp) > -1) {
          arr.push(item)
        }
      } else {
        if (temp == value) {
          arr.push(item)
        }
      }
    }

    return arr
  },
  pluck: function (objArray, key) {
    var values = []
    if (!key) {
      return objArray
    }

    try {
      var temp
      var item
      for (var i = 0, len = objArray.length; i < len; i++) {
        item = objArray[i]
        temp = (key instanceof Array) ? item[key[0]][key[1]] : item[key]
        if (temp === undefined) {
          continue
        }
        values.push(temp)
      }
      return values
    } catch (e) {
      return values
    }
  },
  template: function (str, map) {
    if (!str) return ''
    var tmp
    var re
    var codeRe
    for (var k in map) {
      re = new RegExp('\\{(\\-)*\\s*' + k + '\\s*\\}', 'gim')
      codeRe = new RegExp('\\{\\-\\s*' + k + '\\s*\\}', 'gim')
      tmp = map[k]
      tmp = tmp === undefined ? '' : tmp
      if (codeRe.test(str)) {
        tmp = T.htmlEncode(tmp)
      }
      str = str.replace(re, tmp)
      re = codeRe = null
    }
    return str
  },
  cookie: {
    get: function (name) {
      if (!name) {
        return ''
      }
      var cookie = document.cookie || ''
      let reg = new RegExp('(^|(;\\s*))' + name + '=[^;]+', 'gi')
      let value = (cookie.match(reg) || [])[0] || ''
      value = value.replace(/[\s;]*/gi, '').split('=')[1] || ''

      return value
    },
    set: function (name, value, param) {
      var text = encodeURIComponent(name) + '=' + encodeURIComponent(value)
      param = param || {}
      param.path = param.path || '/'
      var expires = param.expires
      if (expires instanceof Date) {
        text += ';expires=' + expires.toGMTString()
      } else if (typeof expires === 'number') {
        text += ';expires=' + new Date(expires).toGMTString()
      }
      if (param.path) {
        text += ';path=' + param.path
      }
      if (param.domain) {
        text += ';domain=' + param.domain
      }
      if (param.secure) {
        text += ';secure'
      }
      document.cookie = text
    },
    unset: function (name, path, domain, secure) {
      this.set(name, '', new Date(0), path, domain, secure)
    }
  },
  fetch2 (opt) {
    var param = {
      method: opt.method || 'post',
      credentials: 'same-origin',
      domainType: opt.domainType || 'ajax2'
    }

    // 其他id没有数据  先写死
    let userId = T.cookie.get('uid') || '75002'
    let channelId = T.cookie.get('channelId') || '106696614682689537'
    if (userId && opt.data && opt.data.userId === '') {
      opt.data.userId = userId
      opt.data.uid = userId
      opt.data.channelId = channelId
    }

    opt.url = opt.url.replace(/^\//, '')
    if (opt.method !== 'get') {
      param.body = opt.data ? JSON.stringify(opt.data) : ''
    }

    if (opt.data instanceof FormData) {
      param.body = opt.data
    }

    let url = T.host + '/' + param.domainType + '/' + opt.url
    let noTip = opt.noTip || false
    if (T.host) {
      url = opt.url
    }

    if (!opt.noloading) {
      Toast.loading('loading..', 0)
    }

    return new Promise(function (resolve, reject) {
      fetch(url, param).then((res) => {
        Toast.hide()

        var json = res.json()
        json.then((result) => {
          if (result.success === undefined) {
            result.success = result.code === 0
          }

          if (result.value === undefined) {
            result.value = result.data
          }

          if (result.errorMsg === undefined) {
            result.errorMsg = result.message
          }
          if (!result.success) {
            if (result.errorCode == 'WECHAT_LOGIN_00004') {
              T.showError(window.LangMessage.login_error || '登录信息已失效，请重新登录')
              setTimeout(function () {
                location.href = '/login?backurl=' + encodeURIComponent(location.href)
              }, 2000)
              return
            }
            if (!noTip) {
              if (result.errorMsg === '交易密码错误') {
                result.errorMsg = 'ご入力したパスワードが正しくありません。'
              }
              T.showError(result.errorMsg)
            }
          }
          resolve(result)
        })
      })
    })
  },
  fetch (opt) {
    var param = {
      method: opt.method || 'post',
      credentials: 'same-origin'
    }

    opt.url = opt.url.replace(/^\//, '')
    if (opt.method !== 'get') {
      param.body = opt.data ? JSON.stringify(opt.data) : ''
    }

    if (opt.data instanceof FormData) {
      param.body = opt.data
    }

    let url = T.host + '/ajax/' + opt.url
    let noTip = opt.noTip || false
    if (T.host) {
      url = opt.url
    }

    var loading
    if (!opt.noloading) {
      Toast.loading('loading..', 0)
    }

    return new Promise(function (resolve, reject) {
      fetch(url, param).then((res) => {
        Toast.hide()

        var json = res.json()
        json.then((result) => {
          if (result.success === undefined) {
            result.success = result.code === 0
          }

          if (result.value === undefined) {
            result.value = result.data
          }

          if (result.errorMsg === undefined) {
            result.errorMsg = result.message
          }
          if (!result.success) {
            if (result.errorCode == 'WECHAT_LOGIN_00004') {
              T.showError(window.LangMessage.login_error || '登录信息已失效，请重新登录')
              setTimeout(function () {
                location.href = '/login?backurl=' + encodeURIComponent(location.href)
              }, 2000)
              return
            }
            if (!noTip) {
              if (result.errorMsg === '交易密码错误') {
                result.errorMsg = 'ご入力したパスワードが正しくありません。'
              }
              T.showError(result.errorMsg)
            }
          }
          resolve(result)
        })
      })
    })
  },
  fetchNew (opt) {
    var param = {
      method: opt.method || 'post',
      credentials: 'same-origin'
    }

    opt.url = opt.url.replace(/^\//, '')
    if (opt.method !== 'get') {
      param.body = opt.data ? JSON.stringify(opt.data) : ''
    }
    if (opt.data instanceof FormData) {
      param.body = opt.data
    }
    let url = T.host + '/claim/' + opt.url
    let noTip = opt.noTip || false
    if (T.host) {
      url = opt.url
    }

    var loading
    if (opt.loading) {
      Toast.loading('loading..', 0)
    }

    return new Promise(function (resolve, reject) {
      fetch(url, param).then((res) => {
        Toast.hide()

        var json = res.json()
        json.then((result) => {
          if (result.success === undefined) {
            result.success = result.code === 0
          }

          if (result.value === undefined) {
            result.value = result.data
          }

          if (result.errorMsg === undefined) {
            result.errorMsg = result.message
          }
          if (!result.success) {
            if (result.errorCode == 'WECHAT_LOGIN_00004') {
              T.showError(window.LangMessage.login_error || '登录信息已失效，请重新登录')
              setTimeout(function () {
                location.href = '/login?backurl=' + encodeURIComponent(location.href)
              }, 2000)
              return
            }
            if (!noTip) {
              // T.showError(result.errorMsg);
            }
          }
          resolve(result)
        })
      })
    })
  },
  fetchFusion (opt) {
    var param = {
      method: opt.method || 'post',
      credentials: 'same-origin'
    }

    opt.url = opt.url.replace(/^\//, '')

    let uid = T.cookie.get('uid')
    if (uid && opt.data && param.method === 'post') {
      opt.data.uid = uid
    }

    if (opt.method !== 'get') {
      param.body = opt.data ? JSON.stringify(opt.data) : ''
    }
    if (opt.data instanceof FormData) {
      param.body = opt.data
    }
    let url = T.host + '/fusion/' + opt.url
    let noTip = opt.noTip || false
    if (T.host) {
      url = opt.url
    }

    if (opt.loading) {
      Toast.loading('loading..', 0)
    }

    return new Promise(function (resolve, reject) {
      fetch(url, param).then((res) => {
        Toast.hide()
        var json = res.json()
        json.then((result) => {
          if (result.success === undefined) {
            result.success = result.code === 0
          }

          if (result.value === undefined) {
            result.value = result.data
          }

          if (result.errorMsg === undefined) {
            result.errorMsg = result.message
          }

          if (!result.success) {
            if (result.errorCode === 'WECHAT_LOGIN_00004') {
              T.showError(window.LangMessage.login_error || '登录信息已失效，请重新登录')
              setTimeout(function () {
                location.href = '/login?backurl=' + encodeURIComponent(location.href)
              }, 2000)
              return
            }
            if (!noTip) {
              T.showError(result.errorMsg)
            }
          }
          resolve(result)
        })
      })
    })
  },
  check: {
    // mType:0=检查移动、电信、联通，1=检查必须是移动，默认0
    mobile: function (num, mType) { // 判断是是否是手机号码
      if (!num) { return false }
      num = num.toString()
      if (num.length != 13 && num.length != 11) { return false }
      if (num.length == 11) {
        num = '86' + num
      }
      if (mType == 1) {
        var reg = new RegExp('^8613[4-9][0-9]{8}$|^8615[012789][0-9]{8}$|^8618[23478][0-9]{8}$|^8614[7][0-9]{8}$')
      } else {
        var reg = new RegExp('^86(134|135|136|137|138|139|147|150|151|152|157|158|159|181|182|183|184|187|188|130|131|132|155|156|185|186|145|133|153|170|171|172|173|174|175|176|177|178|179|180|189)\\d{8}$')
      }
      return reg.test(num)
    },
    email: function (text) { // 判断是否是合法邮箱
      if (!text) return false
      text = text.trim()
      // RFC 2822
      var reg = new RegExp("^[a-z0-9\.!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$", 'i')
      var result = reg.test(text)
      return result
    },
    idCard: function (value) {
      value = value + ''
      var num = value.toUpperCase()
      if (!(/(^\d{17}([0-9]|X)$)/.test(num))) {
        return false
      }

      var len, re
      len = num.length
      if (len == 18) {
        re = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/)
        var arrSplit = num.match(re)
        var dtmBirth = new Date(arrSplit[2] + '/' + arrSplit[3] + '/' + arrSplit[4])
        var bGoodDay
        bGoodDay = (dtmBirth.getFullYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4]))
        if (!bGoodDay) {
          return false
        } else {
          var valnum
          var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2)
          var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2')
          var nTemp = 0; var i
          for (i = 0; i < 17; i++) {
            nTemp += num.substr(i, 1) * arrInt[i]
          }
          valnum = arrCh[nTemp % 11]
          if (valnum != num.substr(17, 1)) {
            return false
          }
          return true
        }
      }
      return false
    },
    ios: function () {
      var ua = navigator.userAgent
      if (/iPhone|ipod|iPad/i.test(ua)) {
        return true
      }
      return false
    },
    android: function () {
      var ua = navigator.userAgent
      if (/Android|Adr/i.test(ua)) {
        return true
      }
      return false
    },
    isMobileDevice: function () {
      var ua = navigator.userAgent
      if (/mobile/i.test(ua)) {
        return true
      }
      return false
    },
    name: function (value) {
      value = value.replace(/\s*$/, '').replace(/^\s*/, '')
      return /^[\u4e00-\u9fa5a-zA-Z\s]{2,}$/.test(value)
      /* /^[\u4e00-\u9fa5a-zA-Z\s]{2,}$/ */
    }

  },
  loginAction: function (callack, obj = {}) {
    T.fetch({
      url: '/user/login.json',
      data: { 'username': obj.userName || '13480951305', 'password': obj.password || 'pzw123456' }
    }).then((res) => {
      if (res.success) {
        console.log('auto logined')
        callack && callack()
      }
    })
  },
  track () { // 埋點
    window._zals = {}
    window._zals['biz'] = 'anan pc'// 这个是bizGroup.业务约定放这儿.
    window._maEvt = [] // 开启自定义事件.一定要写这个. 这是一个开关.不然是默认不打开自定义事件功能.
  },
  formatPrice (num) {
    if (num === undefined) {
      return ''
    }
    num = num + ''
    num = num.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    return num
  },
  cutPrice (price) {
    if (price === undefined) {
      return ''
    }
    return (+price).toFixed(0)
  },
  localStorage: {
    set (key, value) {
      global.localStorage.setItem(key, value)
    },
    get (key, value) {
      return global.localStorage.getItem(key)
    },
    remove (key, value) {
      global.localStorage.removeItem(key)
    },
    clear () {
      global.localStorage.clear()
    }
  },
  sessionStorage: {
    set (key, value) {
      if (typeof value === 'object') {
        value = JSON.stringify(value)
      }
      global.sessionStorage.setItem(key, value)
    },
    get (key, value) {
      return global.sessionStorage.getItem(key)
    },
    remove (key, value) {
      global.sessionStorage.removeItem(key)
    },
    clear () {
      global.sessionStorage.clear()
    }
  },
  getScreenHeight () {
    return window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
  },
  regObj: {
    // 名称允许汉字、字母、数字，域名只允许英文域名
    email: /^(?:\w+\.?)*\w+@(?:\w+\.)+\w+$/,
    name: /^[\u4e00-\u9fa5a-zA-Z\s]{2,}$/,
    hkid: /^((\s?[A-Za-z])|([A-Za-z]{2}))\d{6}(([0−9aA])|([0-9aA]))$/
  },
  validate: {
    email (email) {
      let reg = T.regObj['email']
      return reg.test(email)
    }
  },
  setColor (diyColor) {
    diyColor = '#00B34A' // 这次grab poc 颜色主题
    if (diyColor) {
      T.cookie.set('diyColor', diyColor)
    } else {
      diyColor = diyColor || T.cookie.get('diyColor') || 'red'
    }

    var style = document.createElement('style')
    style.type = 'text/css'
    style.innerHTML = `.diy_background {background-color:${diyColor} !important;}
    .diy_color {color:${diyColor} !important;}
    .diy_border { border-color:${diyColor} !important;}
    .diy_border_bottom-yj { border-color:${diyColor} !important;}`
    document.getElementsByTagName('head').item(0).appendChild(style)
  },
  calculateEndDay (startTime, duringDays) {
    // 根据保险起期和保障时间计算保险止期
    // startTime -- 2018.6.13
    // duringDays -- 3
    if (!startTime || !duringDays) return
    let duringTimeStamp = +duringDays * 3600 * 1000 * 24
    let startTimeStamp = +new Date(startTime)
    let endTimeStamp = startTimeStamp + duringTimeStamp
    let endDate = new Date(endTimeStamp)
    return endDate.getFullYear() + '.' + (endDate.getMonth() + 1) + '.' + (endDate.getDate() - 1)
  },
  getOffset: function (elem, offset) {
    if (document.body.getBoundingClientRect) {
      let docElem = document.documentElement
      let box = elem.getBoundingClientRect()
      return {
        top: box.top + docElem.scrollTop,
        left: box.left + docElem.scrollLeft
      }
    } else {
      if (!offset) {
        offset = {}
        offset.top = 0
        offset.left = 0
      }
      if (elem === document.body) { // 当该节点为body节点时，结束递归
        return offset
      }

      offset.top += elem.offsetTop
      offset.left += elem.offsetLeft

      return T.getOffset(elem.offsetParent, offset)// 向上累加offset里的值
    }
  },
  formatUrl (url) {
    if (!url) {
      return ''
    } else {
      if (url.indexOf('/') < 0) {
        return 'fusion/file/downloadFile?fileUniqueCode=' + url
      } else {
        return url
      }
    }
  }
}

export default T
